package tech.yangzhijie.basic.xinyan;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import tech.yangzhijie.basic.excel.ExcelListener;
import tech.yangzhijie.basic.xinyan.rsa.RsaCodingUtil;
import tech.yangzhijie.basic.xinyan.util.MD5Utils;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

public class Tests {

    public static String post = "https://api.xinyan.com/product/negative/v4/black";
    public static String memberId = "8150711780";
    public static String terminalId = "1901230525";
    public static String encryptType = "MD5";
    public static String versions = "1.4.0";
    public static String pfxName = "config/xinyan/8150711780_pri.pfx";
    public static String pfxPwd = "themis";
    public static String dataType = "json";

    @Test
    public void 测试读EXCEL() throws FileNotFoundException {
        InputStream inputStream = new FileInputStream(new File("E:\\work\\新颜测试数据.xlsx"));
        ExcelListener excelListener = new ExcelListener();
        EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1,Data.class), excelListener);

        for (Object data : excelListener.getDatas()) {
            Data data1 = (Data) data;
            System.out.print(data1);
        }

    }

    @Test
    public void 测试写EXCEL() throws IOException {
        OutputStream out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\新建 Microsoft Excel 工作表 (2).xlsx");
        ExcelWriter writer = EasyExcelFactory.getWriter(out);

        //写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
        Sheet sheet1 = new Sheet(1, 0);
        //sheet1.setAutoWidth(Boolean.TRUE);
        writer.write1(create(), sheet1);
        //关闭资源
        writer.finish();
        out.close();
    }

    private List<List<Object>> create() {
        List<List<Object>> lists = new ArrayList<>();
        List<Object> list1 = new ArrayList<>();
        list1.add("idname");list1.add("id_card");list1.add("mobile");list1.add("xinyan_response");
        lists.add(list1);
        for(int i=0;i<100;i++){
            List<Object> list = new ArrayList<>();
            list.add("牛宇");list.add("511528199606135627");list.add("15956999417");list.add("{\"success\":true,\"data\":{\"fee\":\"N\",\"code\":\"0\",\"desc\":\"查询成功\",\"trans_id\":\"20190411231125612\",\"trade_no\":\"20190411231126975000007014339411\",\"id_no\":\"dfdad0f5cd2458b4f6326ae955c7b41e\",\"id_name\":\"caffee8e09950d47755d03a95303bb27\",\"versions\":\"1.4.0\",\"result_detail\":{\"currently_overdue\":\"0\",\"max_overdue_amt\":null,\"acc_sleep\":\"1\",\"currently_performance\":\"2\",\"result_code\":\"4\",\"max_overdue_days\":null,\"latest_overdue_time\":null,\"acc_exc\":\"0\"}},\"errorCode\":null,\"errorMsg\":null}");
            lists.add(list);
        }
        return lists;
    }

    @Test
    public void name() throws IOException {

        long l = System.currentTimeMillis();
        String name = "牛宇";
        String idCard = "511528199606135627";
        String mobile = "15956999417";
        String http = http(name, idCard, mobile);
        System.out.println(http);
        System.out.println(System.currentTimeMillis()-l);
    }

    public String http(String name, String idCard, String mobile) {
        try {
            String transId = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now());

            JSONObject content = new JSONObject();
            content.put("member_id", memberId);
            content.put("terminal_id", terminalId);
            content.put("trans_id", transId);
            content.put("trade_date", DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()));
            content.put("encrypt_type", encryptType);
            content.put("id_no", MD5Utils.encryptMD5(idCard));
            content.put("id_name", MD5Utils.encryptMD5(name));
            content.put("phone_no", MD5Utils.encryptMD5(mobile));
            content.put("versions", versions);

            String dataContent = new String(new Base64().encode(JSON.toJSONString(content).getBytes("UTF-8"))).replaceAll("\r\n", "");
            dataContent = RsaCodingUtil.encryptByPriPfxFile(dataContent, "D:\\admin\\dev\\workspace\\demo\\excel\\src\\main\\resources\\8150711780_pri.pfx", pfxPwd);

            String json = "member_id=" + memberId + "&terminal_id=" + terminalId + "&data_type=" + dataType + "&data_content=" + dataContent;
            return OkHTTPClient.post(Tests.post, json);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    private static final Executor executor = Executors.newFixedThreadPool(2000);

    @Test
    public void 测试写和读EXCEL() {
        try (InputStream inputStream = new FileInputStream(new File("E:\\work\\新颜测试数据.xlsx"))) {
            ExcelListener excelListener = new ExcelListener();
            EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1, Data.class), excelListener);
            List<Object> datas = excelListener.getDatas();
            /*List<Object> list = new ArrayList<>(100);
            for (int i = 0; i < 1000; i++) {
                list.add(datas.get(i));
            }*/

            List<List<Object>> execute = execute(datas);

            OutputStream out = new FileOutputStream("E:\\work\\新颜返回数据5.xlsx");
            ExcelWriter writer = EasyExcelFactory.getWriter(out);
            Sheet sheet1 = new Sheet(1, 0);
            sheet1.setAutoWidth(Boolean.TRUE);
            writer.write1(execute, sheet1);
            //关闭资源
            writer.finish();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<Object> execute(Data data){
        List<Object> list = new ArrayList<>();
        list.add(data.getId());
        list.add(data.getName());
        list.add(data.getIdCard());
        list.add(data.getMobile());
        list.add(sleep());
        return list;
    }

    private List<List<Object>> execute(List<Object> list){

        List<CompletableFuture<List<Object>>> collect = list.stream().map(data -> CompletableFuture.supplyAsync(() -> {
            Data data1 = (Data) data;
            List<Object> list2 = new ArrayList<>();
            list2.add(data1.getId());
            list2.add(data1.getName());
            list2.add(data1.getIdCard());
            list2.add(data1.getMobile());
            list2.add(sleep());
            return list2;
        }, executor)).collect(Collectors.toList());
        List<List<Object>> collect1 = collect.stream().map(CompletableFuture::join).collect(Collectors.toList());
        return collect1;
    }

    private double calculatePrice(String product) {
        Random random = new Random();
        return random.nextDouble() * product.charAt(0) + product.charAt(1);
    }

    private String sleep(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "{\"success\":true,\"data\":{\"fee\":\"N\",\"code\":\"0\",\"desc\":\"查询成功\",\"trans_id\":\"20190411231125612\",\"trade_no\":\"20190411231126975000007014339411\",\"id_no\":\"dfdad0f5cd2458b4f6326ae955c7b41e\",\"id_name\":\"caffee8e09950d47755d03a95303bb27\",\"versions\":\"1.4.0\",\"result_detail\":{\"currently_overdue\":\"0\",\"max_overdue_amt\":null,\"acc_sleep\":\"1\",\"currently_performance\":\"2\",\"result_code\":\"4\",\"max_overdue_days\":null,\"latest_overdue_time\":null,\"acc_exc\":\"0\"}},\"errorCode\":null,\"errorMsg\":null}";
    }

    @Test
    public void 获取新颜数据并写入EXCEL() {
        try (InputStream inputStream = new FileInputStream(new File("D:/download/wechat/WeChat Files/haishui12138/Files/新颜测试数据0411.xlsx"))) {
            ExcelListener excelListener = new ExcelListener();
            EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1, Data.class), excelListener);
            List<CompletableFuture<List<Object>>> collect = excelListener.getDatas().stream().map(data -> CompletableFuture.supplyAsync(() -> {
                Data data1 = (Data) data;
                List<Object> list2 = new ArrayList<>();
                list2.add(data1.getId());
                list2.add(data1.getName());
                list2.add(data1.getIdCard());
                list2.add(data1.getMobile());
                list2.add(http(data1.getName(),data1.getIdCard(),data1.getMobile()));
                return list2;
            }, executor)).collect(Collectors.toList());
            List<List<Object>> collect1 = collect.stream().map(CompletableFuture::join).collect(Collectors.toList());

            OutputStream out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\新颜返回数据4.xlsx");
            ExcelWriter writer = EasyExcelFactory.getWriter(out);

            //写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
            Sheet sheet1 = new Sheet(1, 0);
            sheet1.setAutoWidth(Boolean.TRUE);
            writer.write1(collect1, sheet1);
            //关闭资源
            writer.finish();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
